﻿using System;
using System.Collections.Generic;
using System.Text;
using NHibernate.UserTypes;
using NHibernate.SqlTypes;
using System.Data;
using NHibernate;

namespace Technoera.Common.Nh.CustomTypes
{
    public class UriType: IUserType
    {
        #region IUserType Members

        public object Assemble(object cached, object owner)
        {
            return DeepCopy(cached);
        }

        public override bool Equals(object obj)
        {
            Uri other = obj as Uri;
            if (other == null)
                return false;

            return other.ToString() == this.ToString();
        }

        public new bool Equals(object x, object y)
        {

            if (x == y) return true;

            if (x == null || y == null) return false;

            return x.Equals(y);

        }

        public override int GetHashCode()
        {
            return this.ToString().GetHashCode();
        }

        public object DeepCopy(object value)
        {
            if (value == null)
                return null;

            return new Uri(value.ToString());
        }

        public object Disassemble(object value)
        {
            return DeepCopy(value);
        }

        public int GetHashCode(object x)
        {
            if (x == null)
                return 0;

            return x.GetHashCode();
        }

        public bool IsMutable
        {
            get { return false; }
        }

        public object NullSafeGet(IDataReader rs, string[] names, object owner)
        {
            string res = rs[names[0]] as string;

            if (res == null)
                return null;

            return new Uri(res);
        }

        public void NullSafeSet(IDbCommand cmd, object value, int index)
        {
            object newValue = (value == null ? (object)DBNull.Value : (object) value.ToString());
            NHibernateUtil.String.NullSafeSet(cmd, newValue, index);
        }

        public object Replace(object original, object target, object owner)
        {
            return original;
        }

        public Type ReturnedType
        {
            get { return typeof(Uri); }
        }

        public SqlType[] SqlTypes
        {
            get { return new SqlType[] { new SqlType(DbType.String) }; }
        }

        #endregion
    }
}
